<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\api\controller;


use app\api\logic\IndexLogic;
use app\common\model\card\Card;
use app\common\model\finance\{TransactionRecord,TransactionRecordOther};
use think\response\Json;
use payment\{WorldFirstService, AirwallexService, SlashService};
use think\facade\Log;
use think\facade\Db;

/**
 * index
 * Class IndexController
 * @package app\api\controller
 */
class IndexController extends BaseApiController
{


    public array $notNeedLogin = ['index', 'config', 'policy', 'decorate'];


    /**
     * @notes 首页数据
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 段誉
     * @date 2022/9/21 19:15
     */
    public function index()
    {
//        $slash = new SlashService(12);
//        $params = [
////            'filter:from_date' => 1752148800000,
////            'filter:to_date' => 1752152399999,
////            'filter:status' => 'posted'
//        ];
//        $result = $slash->getTransaction($params);
//        dump($result);
//        exit;

//        $slash = new SlashService(15);
//        $result = $slash->getCardList();
//        dump($result);
//        exit;





//        dump(config('billing_custom'));
//        $tid = '2025072919154019034211308120573';
//        if(isset(config('billing_custom')[$tid])){
//            $currey = 'USD';
//            $BILL = config('billing_custom')[$tid];
//            dump($BILL);
//        }
//        exit;
//        $cardId = 'c_2pa3ux17u4ajb';
//        $params = [
//            'filter:cardId' => $cardId,
//        ];
//
//        $hasMore = true;
//        while ($hasMore) {
//            $slash = new SlashService();
//            $result = $slash->getTransaction($params);
//            dump($result);
//            if (isset($result['items'])) {
//                foreach ($result['items'] as $item) {
//                    dump($item);
//                    $merchantCode = $item['merchantData']['categoryCode'] ?? 0;
//                    dump($merchantCode);
//                    if ($merchantCode == 7999) {
//
//                        $code = substr($item['merchantData']['description'] ?? '', -4);
//                        dump($code);
//                        if (strlen($code) == 4) return ['code' => $code];
//                    }
//                }
//            }
//            if (isset($result['metadata']['nextCursor'])) {
//                $params['cursor'] = $result['metadata']['nextCursor'];
//
//            } else {
//                $hasMore = false;
//            }
//        }
//
//        halt(111);




        $worldFirst  = new WorldFirstService('worldfirst');

        //设置单卡限额
        $cardId = '2025090219027200121217605551155';
//        dump($cardId);
//        $worldFirst->updateCardLimit([
//            'asset_id' => $cardId,
//            'per_card_limit_max' =>  990000,
//        ]);

        $a = $worldFirst->getCardDetail($cardId);
//        $a = $result->updateCardStatus($cardId,'UNFREEZE');
//        $worldFirstResult = $worldFirst->getCardList(['card_nick_name' => '20250812150623271000']);
//        $params = [
//            'pageNumber' => 1,
//            'pageSize' => 30,
//            'startTime' => date('c', strtotime("-30 days")),
//            'endTime' => date('c'),
//        ];
//        $worldFirstResult = $worldFirst->getTransactionList($params);
//        dump($worldFirstResult);



        dump($a);
        exit;



//        $config = config('worldfirst_hk');
//
//        // 1. 公钥和私钥（假设你已将公钥保存为 PEM 格式）
//        $publicKey = $config['public_pem'];
//
//        $privateKey = $config['private_key_content'];
//
//// 2. 要加密的数据
//        $plaintext = "Hello, this is a secret message.";
//
//// 3. 使用公钥加密
//        function encryptWithPublicKey($data, $publicKey) {
//            openssl_public_encrypt(
//                $data,
//                $encrypted,
//                openssl_pkey_get_public($publicKey),
//                OPENSSL_PKCS1_OAEP_PADDING
//            );
//            return base64_encode($encrypted);
//        }
//
//// 4. 使用私钥解密
//        function decryptWithPrivateKey($encryptedData, $privateKey) {
//            $encrypted = base64_decode($encryptedData);
//            openssl_private_decrypt(
//                $encrypted,
//                $decrypted,
//                openssl_pkey_get_private($privateKey),
//                OPENSSL_PKCS1_OAEP_PADDING
//            );
//            return $decrypted;
//        }
//
//// 5. 执行加解密
//        $encrypted = encryptWithPublicKey($plaintext, $publicKey);
//        $decrypted = decryptWithPrivateKey($encrypted, $privateKey);
//
//// 6. 输出结果
//        echo "原始数据: " . $plaintext . "\n";
//        echo "加密数据: " . $encrypted . "\n";
//        echo "解密数据: " . $decrypted . "\n";
        // 测试默认配置
//        $worldFirstService = new WorldFirstService();
        
        // 测试指定配置
//        $result  = new WorldFirstService('worldfirst');
//        $a = $result->queryContactList();
//        dump($a);
//        exit;
        
        // 可以通过反射或其他方式验证配置是否正确加载
        // 这里只是示例，实际使用时可以根据需要调用相应的方法
        
//        return $this->success('WorldFirstService配置测试完成');
    }

    private function update_card_detail($cardId)
    {
        $card = Card::where('card_id', $cardId)->findOrEmpty();
        if ($card->isEmpty()) {
            return [];
        }
        $row = [];
        //万里付
        if ($card['card_bin'] == 10) {
            $worldFirst = new WorldFirstService();
            $result = $worldFirst->getCardDetail($card['card_id']);
            if (isset($result['cardLimitDetail']['monthlyLimit'])) {

                $row = [
                    'spend_money' => $result['cardLimitDetail']['monthlyLimit']['used']['value'] / 100,
                    'limit_money' => $result['cardLimitDetail']['monthlyLimit']['range']['value'] / 100
                ];
                Card::where('card_id', $card['card_id'])->update($row);
            }
        }
        //slash
        if ($card['card_bin'] == 12) {
            $slashService = new SlashService(12);
            $result = $slashService->getCardUtilization($card['card_id']);
            if (isset($result['spend']['amountCents'])) {

                $available = $result['availableBalance']['amountCents'] ?? 0;
                $row = [
                    'spend_money' => $result['spend']['amountCents'] / 100,
                ];
                if ($available) $row['limit_money'] = ($available + $result['spend']['amountCents']) / 100;
                Card::where('card_id', $card['card_id'])->update($row);
            }
        }
        return $row;
    }

    /**
     * @notes 全局配置
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 段誉
     * @date 2022/9/21 19:41
     */
    public function config()
    {

        $result = IndexLogic::getConfigData();
        return $this->data($result);
    }


    /**
     * @notes 政策协议
     * @return Json
     * @author 段誉
     * @date 2022/9/20 20:00
     */
    public function policy()
    {
        $type = $this->request->get('type/s', '');
        $result = IndexLogic::getPolicyByType($type);
        return $this->data($result);
    }


    /**
     * @notes 装修信息
     * @return Json
     * @author 段誉
     * @date 2022/9/21 18:37
     */
    public function decorate()
    {
        $id = $this->request->get('id/d');
        $result = IndexLogic::getDecorate($id);
        return $this->data($result);
    }


}